import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { getContractInfo } from '@/api/base'

// 合同操作类型枚举
const CONTRACT_OPERATIONS = {
  ADD: 'add',
  EDIT: 'edit',
  CHANGE: 'change'
}

// 文件字段配置
const FILE_FIELDS = ['PhasedFile', 'TDYSJDFile', 'JHYSJDFile', 'JSJDFile']

// 初始化表单数据
const initFormData = () => ({
  Main: {},
  SubList: [],
  TremQA: [],
  TremTO: [],
  TremDR: [],
  TremFM: [],
  TremD: [],
  TremTC: [],
  TremYS: [],
  TremOther: [],
  TremBM: [],
  TremJF: [],
  TremBZ: [],
  ContractFile: [],
  TremZF: []
})

export const useContractStore = defineStore('contract', {
  state: () => ({
    // 合同基础数据
    contractId: null,
    // 操作类型：add-新增，edit-修改，change-变更
    operationType: 'add',
    formData: {
      Main: {},
      SubList: [],
      TremQA: [],
      TremTO: [],
      TremDR: [],
      TremFM: [],
      TremD: [],
      TremTC: [],
      TremYS: [],
      TremOther: [],
      TremBM: [],
      TremJF: [],
      TremBZ: [],
      ContractFile: [],
      TremZF: []
    },
    loading: false,
    isShowSubBut: false,
    isBg: false,
    isAdd: false,
    dialogSelectEnt: false,
    title: ''
  }),

  getters: {
    // 是否可编辑
    isEditable: (state) => ['add', 'edit'].includes(state.operationType),
    // 是否为变更操作
    isChange: (state) => state.operationType === 'change'
  },

  actions: {
    // 初始化合同操作
    async initContract(type, id = null) {
      const operationConfig = {
        [CONTRACT_OPERATIONS.ADD]: {
          title: '新增合同录入',
          needFetch: false
        },
        [CONTRACT_OPERATIONS.EDIT]: {
          title: '修改合同录入',
          needFetch: true
        },
        [CONTRACT_OPERATIONS.CHANGE]: {
          title: '合同变更',
          needFetch: true
        }
      }

      const config = operationConfig[type]
      if (!config) {
        ElMessage.error('无效的操作类型')
        return
      }

      this.operationType = type
      this.contractId = id
      
      if (!config.needFetch) {
        this.resetState()
        this.title = config.title
        this.isAdd = type === CONTRACT_OPERATIONS.ADD
        this.dialogSelectEnt = true
        return
      }

      try {
        this.setLoading(true)
        const res = await getContractInfo({ id })
        
        if (res.Code === 'OK') {
          this.setFormData(res.Data)
          this.handleFileArrays()
          this.title = config.title
          this.isShowSubBut = true
          this.dialogSelectEnt = true
          if (type === CONTRACT_OPERATIONS.CHANGE) {
            this.isBg = true
          }
        } else {
          throw new Error(res.Message || '获取合同信息失败')
        }
      } catch (error) {
        ElMessage.error(error.message || '获取合同信息失败')
      } finally {
        this.setLoading(false)
      }
    },

    // 初始化新增合同
    async initAddContract() {
      await this.initContract(CONTRACT_OPERATIONS.ADD)
    },

    // 初始化修改合同
    async initEditContract(id) {
      await this.initContract(CONTRACT_OPERATIONS.EDIT, id)
    },

    // 初始化变更合同
    async initChangeContract(id) {
      await this.initContract(CONTRACT_OPERATIONS.CHANGE, id)
    },

    // 处理文件数组转换
    handleFileArrays() {
      FILE_FIELDS.forEach(field => {
        const value = this.formData.Main[field]
        this.formData.Main[field] = value ? value.split(',') : []
      })
    },

    // 关闭弹窗
    closeDialog() {
      this.dialogSelectEnt = false
      this.resetState()
    },
    setFormData(data) {
      this.formData = data
    },
    setLoading(status) {
      this.loading = status
    },
    setShowSubBut(status) {
      this.isShowSubBut = status
    },
    setBg(status) {
      this.isBg = status
    },
    setAdd(status) {
      this.isAdd = status
    },
    setDialogSelectEnt(status) {
      this.dialogSelectEnt = status
    },
    setTitle(title) {
      this.title = title
    },
    resetState() {
      this.formData = {
        Main: {},
        SubList: [],
        TremQA: [],
        TremTO: [],
        TremDR: [],
        TremFM: [],
        TremD: [],
        TremTC: [],
        TremYS: [],
        TremOther: [],
        TremBM: [],
        TremJF: [],
        TremBZ: [],
        ContractFile: [],
        TremZF: []
      }
      this.loading = false
      this.isShowSubBut = false
      this.isBg = false
      this.isAdd = false
      this.dialogSelectEnt = false
      this.title = ''
    }
  }
})